//
//  BN_ChatHostPageData.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-5-12.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_ChatHostPageData.h"
#import "BN_FaceChatViewController.h"

@implementation BN_ChatHostPageData

- (id)init {
    if (self = [super init]) {
        
        if (!_chatHelper) {
            _chatHelper = [[BN_ChatHelper alloc]init];
        }
        if (!self.netArray) {
            self.netArray = [[NSMutableArray alloc]init];
        }
        // 数据请求
        [self performSelectorInBackground:@selector(loadNetData) withObject:nil];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshChatHostPageList) name:KREFRESH_CHATHOSTLIST object:nil];
    }
    return self;
}

- (void)toChatListReload:(ChatListReload) chatListReload {
    self.chatListReload = chatListReload;
}

- (void)loadNetData {
    
    __weak typeof(self) weakSelf = self;
    [_chatHelper queryChatList:^(id result, NSString *errMsg) {
        // update by jason yan 2014-05-30
        if (errMsg) {
            [LZCHINT title:errMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
            weakSelf.chatListReload(YES);
        }
        if(result){
            [weakSelf dealNetArray:result];
            weakSelf.chatListReload(YES);
        }
    }];
}

- (void)refreshChatHostPageList {
    [self loadNetData];
}

- (void)dealNetArray:(id)info {
    NSArray *receiveArr = (NSArray *)info;
    if (receiveArr.count <= 0) {
        [LZCHINT title:@"暂无数据" type:LZCError duration:2 places:@[oriLoca,dispLoca] callBack:NULL];
    }
    [self.netArray setArray:receiveArr];
}

#pragma mark
#pragma mark 列表委托和数据源

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.netArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"BN_ChatHostPageCell";
    BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([BN_ChatHostPageCell class]) bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
        nibsRegistered = YES;
    }
    
    BN_ChatHostPageCell *cell = (BN_ChatHostPageCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    cell.contentView.backgroundColor = [UIColor clearColor];
    
    // 头像
    UIImage *parentImg = [UIImage imageNamed:@"userPhoto"];
    // cell.userPhoto.image = parentImg;
    CGSize size = CGSizeMake(300,300);  // 设置尺寸
    cell.userPhoto.image = [UIImage createRoundedRectImage:parentImg size:size radius:150];
    
    cell.userName.text = FORMAT_STR(_netArray[indexPath.row][@"userName"]);
    
    cell.userName.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:15];
    
    cell.userContent.text = [NSString stringWithFormat:@"%@",_netArray[indexPath.row][@"cont"]];
    [cell sizeToFit];
    
    // 时间
    NSString *dateStr = self.netArray[indexPath.row][@"chatDate"];
    NSRange rang = NSMakeRange(0, 19);
    NSString *strRang = [dateStr substringWithRange:rang];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dateTime = [formatter dateFromString:strRang];
    cell.createTime.text = [IMB_TimeFormatModel timeFormat:dateTime];

    // userId
    NSString *userId_ = self.netArray[indexPath.row][@"userId"];
    cell.tag = [userId_ integerValue];
    
    // 未读状态
    cell.newsStr = self.netArray[indexPath.row][@"news"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 通知聊聊主界面push到聊天对话界面
    BN_ChatHostPageCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    self.userId = [NSString stringWithFormat:@"%ld",(long)cell.tag];
    NSDictionary *dict = [[NSDictionary alloc]init];
    dict = @{@"userId": self.userId,@"userName":cell.userName.text};
    [[NSNotificationCenter defaultCenter]postNotificationName:KPUSHFACECHATVC object:dict];
}

- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // 列表开始加载，开始数据请求
    // [self loadNextNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self loadNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

#pragma mark - 刷新控件的代理方法
#pragma mark 开始进入刷新状态
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    switch ([refreshView viewType]) {
        case -1:
            [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.85];
            break;
        case 1:
            [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0];
            break;
        default:
            break;
    }
}

#pragma mark 刷新完毕
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    // NSLog(@"%@----刷新完毕", refreshView.class);
}

#pragma mark 监听刷新状态的改变
- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            break;
            
        case MJRefreshStatePulling:
            break;
            
        case MJRefreshStateRefreshing:
            break;
        default:
            break;
    }
}

#pragma mark
#pragma mark 生命周期
- (void)dealloc
{
    NSLog(@"聊聊主页Modal释放...");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KPUSHFACECHATVC object:nil];

}

@end
